#!/bin/sh

PATH=/usr/portage/scripts/:$PATH
[ "$DESTDIR" = "" ] && DESTDIR=${PWD}/binroot
[ "$RWORLD" = "" ] && RWORLD=/etc/portage/soekris/PACKAGES

PKGDIR=/usr/portage/packages/

if ! type -p tbz2ipkg >/dev/null; then
	mkdir -p /usr/portage/scripts/
	wget -P /usr/portage/scripts/ http://dev.gentoo.org/~solar/portage_misc/tbz2ipkg
fi

function repackage() {
	local ok=1

	mkdir -p tmp ${DESTDIR}

	args=$*
	for f in $args ; do
		for x in $(ls -1 ${PKGDIR}/All/${f}*.tbz2 ); do
			p=${PKGDIR}/All/$(basename $x .tbz2).ipk
			[ -e ${p} ] || tbz2ipkg $x
			x=$p
			if [ -e $x ]; then
				rm -rf tmp/ipkg
				mkdir -p tmp/ipkg/$x
				tar zxf $x -C tmp/ipkg/$x && \
					cd tmp/ipkg/$x && \
					echo -ne '\033[1;33m>>>\e[0;0m ' && \
					echo "Installing $(basename $x) to ${DESTDIR}" && \
					gzcat data.tar.gz | tar -xf - -C ${DESTDIR} && \
					cd -
				rm -rf tmp/ipkg
			fi
		done
	done
}

if [ "$1" == "update" ]; then
	wget --passive-ftp -P //dev/shm/tmp/ipkg http://oc12.net/~solar/gentoo/uclibc/x86/packages/ipkg//Packages
	exit 0
fi

if [ "$1" == "list" ]; then
	grep ^[A-Za-z0-9] ${RWORLD}  | cut -d : -f 1 | while read f; do
		ls -1 ${PKGDIR}/All/${f}*.tbz2 2>/dev/null | grep [a-zA-Z0-9] | while read x ; do 
			[ -e $x ] && basename $x .tbz2
		done
	done
	exit 0
fi

if ([ "$1" == "install" ]; ); then
	[ -e "${DESTDIR}" ] && continue;

	shift

	if [ "$1" == "" ] ; then
		grep ^[a-zA-Z0-9] ${RWORLD}  | cut -d : -f 1 | while read f ; do
			repackage $f
		done
	else
		repackage $*
	fi

	cd ${DESTDIR}

	rm -f ./usr/bin/{encode_keychange,snmp{get,getnext,set,usm,walk,bulkwalk,table,trap,bulkget,translate,status,delta,test,df,vacm,netstat}}
	rm -rf ./usr/share/snmp/snmpconf-data  ./usr/bin/snmpc{heck,onf} ./usr/share/snmp/*.conf

	find . -name '*.example' -o -name '*.sample' | grep ample | xargs rm -f

	# USE perl?
	[ $(find . -name '*.pl' | wc -l) = 0 ] || ( find . -name '*.pl' -exec rm -f '{}' \; )

	#find . -type f  | xargs -n1 file | grep "perl script text executable" | cut -d : -f 1 | xargs -n1 rm -f

	echo -e '\e[1;35m>>>\e[0m Done '
	du -chs .| tail -n1 

fi
